import { createStore } from 'vuex'
const setLocalCartList = (state) => { // 购物车信息
  const { cartList } = state;
  const cartListString = JSON.stringify(cartList);
  localStorage.cartList = cartListString;
}
const getLocalCartList = () => {
  return JSON.parse(localStorage.cartList || "{}");
}
export default createStore({
  state: {
    // 数据结构如下所示
    cartList: getLocalCartList()
    // shopId: {
    //   shopName: "沃尔玛",
    //   productList: {
    //     productId: {
    //       id: 1,
    //       name: "番茄250g/份",
    //       imgUrl: "http:...",
    //       sales: 10,
    //       price: 33.6,
    //       oldPrice: 39.6,
    //       count: 2
    //     }
    //   }
    // }
  },
  mutations: {
    changeItemToCart(state, payload) {
      const { shopId, productId, productInfo, num } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: '', productList: {}
      };
      let product = shopInfo.productList[productId];
      if (!product) {
        product = productInfo;
        product.count = 0;
      };
      product.count = product.count + num;
      if (num > 0) { product.checked = true; }
      if (product.count < 0) { product.count = 0; }
      shopInfo.productList[productId] = product;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    changeShopName(state, payload) {
      const { shopId, shopName } = payload;
      const shopInfo = state.cartList[shopId] || {
        shopName: '', productList: {}
      };
      shopInfo.shopName = shopName;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state);
    },
    changeCartItemCheck(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.checked = !product.checked;
      setLocalCartList(state);
    },
    handleClearCart(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCartList(state);
    },
    handleCheckAllButton(state, payload) {
      const { shopId } = payload;
      const products = state.cartList[shopId].productList;
      for (const i in products) {
        products[i].checked = !products[i].checked;
      }
      setLocalCartList(state);
    }
  },
  actions: {
  },
  modules: {
  }
})
